const express = require('express');
const path = require('path');
const logger = require('morgan');
const puppeteer = require('puppeteer');

const drawRouter = require('./routes/draw');

async function launchBrowserWithRetry() {
  let browser = null;
  async function launch() {
    try {
      browser = await puppeteer.launch({
        args: ['--no-sandbox', '--disable-setuid-sandbox']
      });
      browser.on('disconnected', async () => {
        console.error('Puppeteer browser disconnected! Restarting...');
        browser = await launch();
        app.locals.browser = browser;
      });
      return browser;
    } catch (e) {
      console.error('Failed to launch Puppeteer, retrying in 2s...', e);
      await new Promise(res => setTimeout(res, 2000));
      return await launch();
    }
  }
  return await launch();
}

const app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use('/draw', drawRouter);
app.use(express.static(path.join(__dirname, 'public')));

// Puppeteer browser init
launchBrowserWithRetry().then(browser => {
  app.locals.browser = browser;
  console.log('Puppeteer browser started.');
});

module.exports = app;
